// Requires "request" to be installed (see https://www.npmjs.com/package/request)
var request = require('request');
var fs = require('fs');

const removebgFuntion = (imageName, callback) => {
  let resultImage = __dirname + "/pixian/" + Date.now() + "-pixian.png";
  request.post({
    url: 'https://api.pixian.ai/api/v1/remove-background',
    formData: {
      image: fs.createReadStream('./uploads/' + imageName), // TODO: Replace with your image
      // TODO: Add more upload options here
    },
    auth: { user: 'pxynk6n7gayvrvk', pass: 'h5lrsm328ajen9mn1erpmscqntige63ahpadu1c5cmaa13sl0rod' },
    followAllRedirects: true,
    encoding: null
  }, function (error, response, body) {
    if (error) {
      console.error('Request failed:', error);
    } else if (!response || response.statusCode != 200) {
      console.error('Error:', response && response.statusCode, body.toString('utf8'));
    } else { 
      // Save result
      fs.writeFileSync(resultImage, body);
      callback(resultImage);
    }
  });
  return resultImage;
};

module.exports = removebgFuntion;
